package com.kedacom.ctsp.authz.oauth2.provider;

import com.kedacom.ctsp.authority.entity.User;
import com.kedacom.ctsp.authority.service.UserService;
import com.kedacom.ctsp.authz.AuthenticationService;
import com.kedacom.ctsp.authz.access.DefaultDataAccessHandler;
import com.kedacom.ctsp.authz.entity.AuthResource;
import com.kedacom.ctsp.authz.entity.AuthzTypeEnum;
import com.kedacom.ctsp.authz.oauth2.core.vo.UserQueryParam;
import com.kedacom.ctsp.authz.oauth2.entity.AccessToken;
import com.kedacom.ctsp.authz.oauth2.service.AccessTokenService;
import com.kedacom.ctsp.authz.security.provider.AuthUserDetails;
import com.kedacom.ctsp.orm.param.Term;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;

@Component
public class OAuth2UserResourceQequestFilter {

    @Autowired
    private AuthenticationService authenticationService;

    @Autowired
    private AccessTokenService accessTokenService;

    @Autowired
    private UserService userService;


    @Autowired
    protected DefaultDataAccessHandler defaultDataAccessHandler;

    /**
     * Fegin 通过 accessToken 无登录状态获取用户本人部门、资源等信息，通过权限资源过滤
     *
     * @param param
     */
    public void getUserResourceByaccessTokenFiler(UserQueryParam param) {

        //用户登录信息
        AccessToken auth2AccessEntity = accessTokenService.getTokenByAccessToken(param.getAccessToken());
        if (null == auth2AccessEntity) {
            return;
        }

        //用户信息
        User user = userService.get(auth2AccessEntity.getOwnerId());
        if (user == null) {
            return;
        }

        //把登录信息设置到spring上下文中
        AuthUserDetails principal = new AuthUserDetails(authenticationService.loadUserByUsername(user.getUsername()));

        //用户资源
        List<AuthResource> authResources = authenticationService.loadResources(principal.getAuthentication(), new HashSet<>(), AuthzTypeEnum.ANNOTATION);
        if (CollectionUtils.isEmpty(authResources)) {
            return;
        }

        //添加查询条件
        // 如: 旧的条件为 where name =? and sign = ?
        // 加上数据权限后为: where name = ? and sign = ? and (department_id in(?,?) or dept_id in (?,?))
        List<Term> terms = defaultDataAccessHandler.getDataScopeAndAccessTerms(authResources, principal.getAuthentication(), null);
        if (CollectionUtils.isNotEmpty(terms)) {
            param.addTerms(terms);
        }
    }
}
